import { observable, action, toJS } from 'mobx';
import * as myWorkPlanApi from '../../apis/myWorkPlan';
import * as oneWeekWorkPlanApi from '../../apis/oneWeekWorkplan';


import { WeaTableNew } from 'comsMobx'
const { TableStore } = WeaTableNew;
import moment from 'moment';
import {WeaLocaleProvider} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;


export default class MyWorkPlanStore {
  test = getLabel(18480,'我的日程');
  DATA_FEED_URL = "/workplan/calendar/data/getData.jsp";
  date = new Date();
  @observable loading = false;
  @observable comsWeaTableStore = new TableStore();
  @observable dataKey = '';
  @observable importVisible = false;
  @observable saveLoading=false;
  @observable exportExcelUrl='';
  @observable dialogHeight=0
  @observable userList = [];
  @observable isWorkplanView = false;
  @observable status = {
    loading: false,
    timeType: '',//日月年
    userList: [],
    userRoot: undefined,
    tabOptions: [],//tab下拉参数
    selected: '',//下拉默认值 '' 为全部
    selectedUser: '',//下拉默认值 '' 为全部
    date: new Date(),
    dateMoment: moment(),
    update: false,
    isShare: '',
    activeKey: '1',

    objType: '1',//默认部门,1 部门 2分部 3人力资源
    objIds: [],//请求数据.
    objDepts:[],//部门
    objSubs:[], //分部
    objHrms:[],//人员
    commonIds: [], // 公用
    useMap: {},//key为memberids，value为使用信息
    useMap_pm:{},
    memberids: [],
    workPlanType: '',
    dayOfWeek: [],//周模式-用来匹配哪天
    amAndPm:false,//是否区分上下午
    dataRule:2,//1 创建人 2接收人

    createVisible: false,
    createType: 'preview',
    workPlanId: '',
    createConditionParams: [],

    defBgTime: 0,//defBgTime开始时间的整数
    defEdTime: 24,//；defEdTime结束时间的整数
    defBgTimeStr: "00:00",//defBgTimeStr 开始时间的字符串；
    defEdTimestr: "23:59", //defEdTimestr结束时间的字符串

    attentionData: '',//关注者信息
    spinning: false,//加载中true，加载完毕false
    isInit: '1',
    pageNum: 2,//我的关注页数
    totalPage: 1,//我的关注总页数
    selectedUserName: '',
    weekstartday: 0,
    workPlanShow: 'calender',

    calendarInit: '',

    zone_offset:8,
    titleFold: 0, //1折叠
    isSpinning: false,
    canEWSToOa: false,
    syncDay: 7,
    layoutType: '1',
  }
  @observable weekScrolllwidth = false;
  @observable workplanPreviewTable = false;
  @observable selectHrmType = '';
  @observable typeOption = [];
  @observable hasBrowserVisible = false;
  @observable hasCommonGroupVisible = false;
  @observable hasMyAttentionVisible = false;
  @observable workplanContentDisplayWidth = 0;
  @observable exportListBtnTitle = '';

  @observable oneWeekStatus = {
    selectedOptions: [],
    selectedVal: '',
    DatasList: [],
    showNight: false,
    showNoon: false,
    dateStr: '',
    isIcon1: '1',
    hasDatas: false,
    weekstartday: 1, // 从周一开始
  };
  @observable time4RightCon=Math.random().toString(36).substr(2);
  @action 
  setTime4RightCon = ()=>{
    this.time4RightCon=Math.random().toString(36).substr(2)
  }
  @action
  setParams = (params = {}) => {
    Object.keys(params).forEach(key => {
      this[key] = params[key];
    });
  }
  @action
  setStatusParams = (params = {}, callback) => {
    Object.keys(params).forEach(key => {
      this.status[key] = params[key];
    });
    typeof(callback) === 'function' && callback()
  }
  @action
  setOneWeekParams = (params = {}, callback) => {
    Object.keys(params).forEach(key => {
      this.oneWeekStatus[key] = params[key];
    });
    typeof(callback) === 'function' && callback()
  }
  @action
  changetableScrolllright = (param) => {
    this.weekScrolllwidth = param;
  }

  constructor() {

  }
  
  @action
  getUserList(params) {
    return this.status.userList.slice();
  }

  @action
  doInit = (type, isInit,workPlanShow) => {//初始化
    let attentionParams = workPlanShow === 'list' ? { searchStr: '', pageNum: 1, noLimit: 1} :{ searchStr: '', pageNum: 1 }
    let p1 = myWorkPlanApi.getSelectType({ showAll: 1 })
    let p2 = myWorkPlanApi.getBaseData({})
    let p3 = myWorkPlanApi.getAttentionData(attentionParams);
    let p4 = myWorkPlanApi.getLayoutType({});

    this.status = { ...this.status, isInit: '1', isShare: type ? true : false, workPlanShow:(workPlanShow?workPlanShow:'calender') }
    Promise.all([p1, p2, p3, p4]).then((result) => {
      let selectTemp = '';
      result[0].forEach((v,l) => {
        selectTemp += v.key;
        l !== result[0].length - 1 && (selectTemp += ',');
      })
      this.status.tabOptions = result[0];
      let { timeRangeStart, timeRangeEnd, viewType, weekstartday = 0,titleFold } = result[1];
      let timeRangeEndCopy = timeRangeEnd + 1;
      let defBgTimeStr = timeRangeStart < 10 ? `0${timeRangeStart}:00` : `${timeRangeStart}:00`;
      let defEdTimestr = timeRangeEnd < 10 ? `0${timeRangeEnd}:59` : `${timeRangeEnd}:59`;
      this.status = {
        ...this.status,
        timeType: viewType,
        isShare: type ? true : false,
        //selected: selectTemp,
        date: new Date(),
        dateMoment: moment(),
        userRoot: undefined,
        selectedUser: '',
        defBgTime: timeRangeStart,
        defEdTime: timeRangeEndCopy,
        defBgTimeStr: defBgTimeStr,
        defEdTimestr: defEdTimestr,
        objType: '1',//默认部门,1 部门 2分部 3人力资源
        objIds: [],
        objDepts:result[1].dept?result[1].dept:[],
        objSubs:result[1].subComp?result[1].subComp:[],
        useMap: {},//key为memberids，value为使用信息
        memberids: [],
        workPlanType: '',
        dayOfWeek: [],//周模式-用来匹配哪天
        attentionData: result[2].data,
        totalPage: result[2].totalpage,
        pageNum: 2,//我的关注页数
        spinning: false,
        update: false,
        isInit: 'true',
        selectedUserName: '',
        weekstartday: weekstartday,
        calendarInit: result[1].calendarInit,
        zone_offset:result[1].zone_offset,
        titleFold: titleFold,
        canEWSToOa: result[1].canEWSToOa,
        syncDay: result[1].syncDay,
        layoutType: result[3].syncDay,
      };
      if(result[1]&&result[1].selectGroup) {
        this.typeOption = result[1].selectGroup;
        let type = result[1].selectGroup;
        this.status.objType = type[0].key;
        if(type[0].key === '1' || type[0].key === '2' || type[0].key === '3') {
          this.hasBrowserVisible = true;
        }else if(type[0].key === '6') {
          this.hasCommonGroupVisible = true;
        }else if(type[0].key === '7') {
          this.hasMyAttentionVisible = true;
        }else{
          this.hasBrowserVisible = false;
          this.hasCommonGroupVisible = false;
          this.hasMyAttentionVisible = false;
        }
      }
      if(result[1]&&result[1].exportListBtnTitle) {
        this.exportListBtnTitle = result[1].exportListBtnTitle;
      }
      this.status.workPlanShow === 'list' && this.changeGetCalendarData(); //日程一览表初始化数据
    });
    // myWorkPlanApi.getCalendarData().then(action(result => {
    //   this.status = { ...this.status,dataRule: result.conf.dataRule}
    // }))
  }

  @action
  doEwsToOa = ()=>{
    let { date } = this.status;
    date = this.changeDateFormat(date);
    let params = {
      selectDate: date,
    };
    myWorkPlanApi.syncEwsToWP(params)
  }

  @action
  setDialogHeight=(hegiht)=>{
    this.dialogHeight =hegiht;
  }
  @action
  doattention = (index,searchStr='') => {
    let { page, attentionData } = this.status;
    let attentionParams = { searchStr: searchStr, pageNum: index }
    myWorkPlanApi.getAttentionData(attentionParams).then(result => {

      this.status = { ...this.status, attentionData: result.data, totalPage: result.totalpage, pageNum: index + 1 }
    })

  }
  @action
  changeInit = (bool) => {
    this.status = { ...this.status, isInit: bool }
  }
  @action
  changeSpinning = (bool) => {
    this.status = { ...this.status, spinning: bool }
  }
  @action
  onlyChangeSelectedUser = (selectedUser) => {
    this.status = { ...this.status, selectedUser: selectedUser }
  }
  @action
  changeSelectedUser = (selectedUser, name) => {
    this.status = { ...this.status, selectedUser: selectedUser, selectedUserName: name }
  }
  @action
  changeUserRoot(ids, names, datas) {
    if (datas != '') {
      if (datas == undefined) {
        this.status = { ...this.status, userRoot: datas, selectedUser: '', selectedUserName: '' }
      } else {
        this.status = { ...this.status, userRoot: datas, selectedUser: ids, selectedUserName: names }
      }
    } else {
      this.status = { ...this.status, selectedUser: ids, selectedUserName: names }
    }
  }
  @action
  addAttention = (id, callback) => {
    let attentionParams = {
      touserid: id,
      searchStr: '',
    }
    myWorkPlanApi.addAttention(attentionParams).then(result => {
      typeof(callback) === 'function' && callback();
    })
  }
  @action
  updateAttention = (id, callback) => {
    let attentionParams = {
      touserid: id,
      searchStr: '',
    }
    myWorkPlanApi.updateAttention(attentionParams).then(result => {
      this.status = {
        ...this.status,
        attentionData: result.data,
      };
      typeof(callback) === 'function' && callback();
    })
  }
  @action
  delAttention = (id,callback ) => {
    let attentionParams = {
      touserid: id,
      searchStr: '',
    }
    myWorkPlanApi.delAttention(attentionParams).then(result => {
      callback&&callback();
    })
  }
  @action
  getAttentionData = (attentionParams,callback) => {
    myWorkPlanApi.getAttentionData(attentionParams).then(result => {
      this.status = {
        ...this.status,
        attentionData: result.data,
        pageNum: 1,
        totalPage: result.totalpage
      }
    })
  }
  @action
  changeTab = (e) => {
    this.status = { ...this.status, activeKey: e }
  }
  @action
  getRightMenu() {  
  }
  @action
  onRightMenuClick() {

  }
  @action
  changeType = (value, ids) => {
    value && (this.status = { ...this.status, objType: value })
    this.changeGetCalendarData();
  }
  @action
  getComomnCalendarData = (ids) => { // 常用组获取人员日程信息
    let { date, timeType, objType,commonIds, selected } = this.status;
    date = this.changeDateFormat(date);
    let timeTypeNum = timeType == 'month' ? 3 : timeType == 'day' ? 1 : 2;
    let useMap = {}
    let useMap_pm={}
    let params = {
      bywhat: timeTypeNum,
      selectDate: date,
      objType: objType,
      objIds: commonIds,
      workPlanType: selected,
    };
    // this.changeSpinning(true);
    this.status.isSpinning = true;
    this.status = { ...this.status, useMap: [],useMap_pm:[], memberids: []}; // 清空前一次数据
    myWorkPlanApi.getCalendarData(params).then(action(result =>{
      this.changeSpinning(false);
      this.status.isSpinning = false;
      result.datas && result.datas.forEach((obj) => {
        if (!obj.memberid) return;
        if (obj.info) {
          useMap[obj.memberid] = obj.info;
        }
        if(obj.info_pm){
          useMap_pm[obj.memberid] = obj.info_pm;
        }
      });
      this.status = { ...this.status, useMap: useMap,useMap_pm:useMap_pm, memberids: result.memberids, dayOfWeek: result.days.value,amAndPm:result.conf.ap,dataRule:result.conf.dataRule }
    }));
  }
  @action
  changeBro = (value) => {
    if(this.status.objType==1){
      this.status = { ...this.status, ...{objDepts: value} }
    }else if(this.status.objType==2){
      this.status = { ...this.status, ...{objSubs: value} }
    }else if(this.status.objType==3){
      this.status = { ...this.status, ...{objHrms: value} }
    }

    this.changeGetCalendarData();
  }
  @action
  changeTimeType = (type) => {
    let { workPlanShow } = this.status
    this.status = { ...this.status, timeType: type };
    let viewType = type == 'day' ? 1 : type == 'week' ? 2 : 3
    myWorkPlanApi.setViewType({ viewType: viewType });
    workPlanShow == 'list' && this.changeGetCalendarData();
  }
  @action
  search = (params) => {
    let { workPlanShow } = this.status;
    this.status = { ...this.status, date: new Date(), dateMoment: moment() }
    workPlanShow == 'list' && this.changeGetCalendarData();
  }
  @action
  changeOptions = (params, type, moment) => {
    let { workPlanShow } = this.status
    if (type == 'status') {
      this.status = { ...this.status, selected: params };
      workPlanShow == 'list' && this.changeGetCalendarData()
    }
    if (type == 'calendarParams') {
      this.status = { ...this.status, date: params, dateMoment: moment };
      workPlanShow == 'list' && this.changeGetCalendarData()
    }
    if (type == 'oneweek') {
      this.status = { ...this.status, date: params, dateMoment: moment };
    }
  }
  @action
  getData = (params) => {
  }
  @action
  close = () => {
    this.status = { ...this.status, createVisible: false, activeKey: '1' }
    this.doUpdateCalender(true);
  }
  @action
  onlyClose = () => {
    this.status = { ...this.status, createVisible: false, activeKey: '1' }
  }
  @action
  open = (params, workPlanId, createConditionParams) => {//params为创建类型，workPlanId为日程id，为创建参数
    this.status = {
      ...this.status,
      createVisible: true,
      createType: params,
      workPlanId: workPlanId,
      createConditionParams: createConditionParams,
    }
  }
  @action
  openImport = () => {
    this.importVisible = true;
  }
  @action
  closeImport = () => {
    this.importVisible = false;
  }
  @action
  doExcelImport = (param) => {
    return  myWorkPlanApi.doExcelImport(param);
  }
  @action
  addExcelFileid = (param,callback) => {
    myWorkPlanApi.addExcelFileid(param).then(data =>{
      if(data.status){
        if(callback instanceof Function){
          callback();
        }
      }
    });
  }
  @action
  doGetShareTable = (workid) => {
    myWorkPlanApi.getShareList({ planID: workid }).then(data => {
      this.comsWeaTableStore.getDatas(data.sessionkey, 1);
      this.dataKey = data.sessionkey;
    })
  }
  @action
  changeShow = (type) => {
    this.status = { ...this.status, workPlanShow: type }
    type == 'calender' && this.doUpdateCalender(true);
    type == 'list' && this.changeGetCalendarData();
  }
  @action
  changeDateFormat = data => {
    if (typeof (data) === 'string' && data != '') {
      return data
    }
    //日期格式转为yyyy-MM-dd
    let now = data || new Date();
    let year = now.getFullYear();
    let month = (now.getMonth() + 1).toString();
    let day = (now.getDate()).toString();
    if (month.length == 1) {
      month = "0" + month;
    }
    if (day.length == 1) {
      day = "0" + day;
    }
    let dateString = year + "-" + month + "-" + day;
    return dateString;
  }
  @action
  changeGetCalendarData = () => {
    this.exportExcelUrl='';
    // this.changeSpinning(true)
    let { objType, objDepts,objSubs,objHrms,commonIds } = this.status;
    let objIds=[];
    if(this.status.objType==1){
      objIds = toJS(objDepts);
    }else if(this.status.objType==2){
      objIds = toJS(objSubs);
    }else if(this.status.objType==3){
      objIds = toJS(objHrms);
    }else{
      this.getComomnCalendarData(commonIds);
    }
    let { dateMoment, selected, timeType, date } = this.status;
    let timeTypeNum = timeType == 'month' ? 3 : timeType == 'day' ? 1 : 2;
    let dateMomentFormat = dateMoment.format("YYYY-MM-DD");
    let objIdsArr = [];
    let objIdsStr = '';
    if (objIds.length > 0) {
      objIds.forEach((element) => {
        objIdsArr.push(element.id)
      })
      objIdsStr = objIdsArr.join(',')
    }

    // selected = selected == -9900 ? '' : selected;
    date = this.changeDateFormat(date)
    let useMap = {}
    let useMap_pm={}
    let params = {
      bywhat: timeTypeNum,
      selectDate: date,
      objType: objType,
      objIds: objIdsStr,
      workPlanType: selected,
    };
    this.status = { ...this.status, useMap: [],useMap_pm:[], memberids: []}; // 清空前一次数据
    objIds.length>0 ? (this.status.isSpinning = true) : '';
    objIds.length>0&&myWorkPlanApi.getCalendarData(params).then(action(result => {
      this.status.isSpinning = false;
      result.datas && result.datas.forEach((obj) => {
        if (!obj.memberid) return;
        if (obj.info) {
          useMap[obj.memberid] = obj.info;
        }
        if(obj.info_pm){
          useMap_pm[obj.memberid] = obj.info_pm;
        }
      });
      this.changeSpinning(false)
      this.status = { ...this.status, useMap: useMap,useMap_pm:useMap_pm, memberids: result.memberids, dayOfWeek: result.days.value,amAndPm:result.conf.ap,dataRule:result.conf.dataRule }
    }))
    if(objIds.length==0){
      this.status = { ...this.status, useMap: [],useMap_pm:[], memberids: []}
      this.changeSpinning(false)
    }

  }
  @action
  doUpdateCalender = (type) => {
    this.exportExcelUrl='';
    if (type == true) {
      this.status = { ...this.status, update: true  ,objIds:[] };
    } else {
      this.status = { ...this.status, update: false ,objIds:[]};
    }
  }
  @action
  setSaveLoading=(b)=>{
    this.saveLoading=b;
  }
  @action
  exportExcel=(excelType)=>{
    this.changeSpinning(true)
    let { objType, objDepts,objSubs,objHrms,commonIds } = this.status;
    const {isIcon1,dateStr,selectedVal,selectedOptions} = this.oneWeekStatus;
    let objIds=[];
    if(this.status.objType==1){
      objIds = toJS(objDepts);
    }else if(this.status.objType==2){
      objIds = toJS(objSubs);
    }else if(this.status.objType==3){
      objIds = toJS(objHrms);
    }
    let { dateMoment, selected, timeType, date, useMap, useMap_pm } = this.status;
    let timeTypeNum = timeType == 'month' ? 3 : timeType == 'day' ? 1 : 2;
    let dateMomentFormat = dateMoment.format("YYYY-MM-DD");
    let objIdsArr = [];
    let objIdsStr = '';
    if (objIds.length > 0) {
      objIds.forEach((element) => {
        objIdsArr.push(element.id)
      })
      objIdsStr = objIdsArr.join(',')
    }

    // selected = selected == -9900 ? '' : selected;
    date = this.changeDateFormat(date)
    // let useMap = {}
    // let useMap_pm={}
    let params = {
      bywhat: timeTypeNum,
      selectDate: date,
      objType: objType,
      objIds: objIdsStr,
      workPlanType: selected,
    };
    if(excelType === 'oneweek') {
      params = {selectDate: dateStr,groupId: selectedVal, styleType: isIcon1};
    }
    excelType === 'list' && (this.exportExcelUrl='/api/workplan/calendar/exportExcelList?'+this.buildUrlStr(params)+'&_t='+new Date().getTime())
    excelType === 'excel' && (this.exportExcelUrl='/api/workplan/calendar/exportExcel4Html?'+this.buildUrlStr(params)+'&_t='+new Date().getTime())
    excelType === 'oneweek' && (this.exportExcelUrl='/api/workplan/calendar/exportWeekPlanExcel4Html?'+this.buildUrlStr(params)+'&_t='+new Date().getTime())
 
    this.changeSpinning(false)
  }

  @action
  buildUrlStr = (params = {}) => {
    let str = "";
    _.forIn(params, (value, key) => {
        str += `&${key}=${value}`;
    });
    if (str !== "")
        str = str.substring(1);
    return str;
  }

  @action
  refreshSelectType=()=>{
    myWorkPlanApi.getSelectType({ showAll: 1 }).then((result)=>{
      let selectTemp='';
      result.forEach((v,l) => {
        selectTemp += v.key;
        l !== result.length - 1 && (selectTemp += ',');
      })
      this.status = {
        ...this.status,
        tabOptions:result,
        //selected:selectTemp
      }
    })
  }

  // 一周日程选择框
  @action
  getWorkPlanWeekGroupSelect = (params, callback) => {
    oneWeekWorkPlanApi.getWorkPlanWeekGroupSelect(params).then(res => {
      if(res.api_status) {
        this.oneWeekStatus = {
          ...this.oneWeekStatus,
          selectedOptions: res.selectGroup&&res.selectGroup.length != 0 ? res.selectGroup : [{ showname: getLabel('509729','暂无可查看的数据'), key: '-1' }],
          selectedVal: res.selectGroup[0] ? res.selectGroup[0].key : '-1',
          weekstartday: res.weekStartDay,
          isIcon1: res.viewType
        }
        typeof(callback) === 'function' && callback({groupId: res.selectGroup[0] ? res.selectGroup[0].key : ''})
      }else{}
    });
  }

  // 一周日程安排日程数据
  @action
  getWorkPlanWeekData = (param) => {
    let params = {
      selectDate: this.oneWeekStatus.dateStr,
      groupId: this.oneWeekStatus.selectedVal,
      ...param
    };
    this.changeSpinning(true)
    oneWeekWorkPlanApi.getWorkPlanWeekData(params).then(res => {
      let bool = false;
      if(res.api_status) {
        this.changeSpinning(false)
        res.datas.map(res => {
          if(res.am || res.pm) {
            bool = true;
            return;
          }
        });
      }
      this.oneWeekStatus = {
        ...this.oneWeekStatus,
        DatasList: res.datas,
        showNight: res.showNight,
        showNoon: res.showNoon,
        hasDatas: bool,
      }
    });
  }
  // 一周日程安排显示视图类型
  @action
  updateWeekViewType = (params) => {
    oneWeekWorkPlanApi.updateWeekViewType(params).then(res =>{

    });
  }
}